package tongcheng.com.tongcheng.widght;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.luck.picture.lib.config.PictureConfig;

import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.bean.MapDataBean;
import tongcheng.com.tongcheng.utils.GsonUtil;
import tongcheng.com.tongcheng.utils.Setting;

import static tongcheng.com.tongcheng.utils.ShowToast.showToast;


/**
 * Created by Administrator on 2016/9/27.
 */
public class MapTopPopWindow {

    private PopupWindow popupWindow;
    private Context mContext;
    private Activity mActivity;
    public int maxChooseNum = 1;
    public int minChooseNum = 1;
    public int single = PictureConfig.SINGLE;
    private String[] data = new String[]{"相册", "拍照"};
    public Marker marker;
    private final MapDataBean.DataBean mDatas;
    private LatLng latLng1;
    private boolean isGeRenQiangDan = false;

    public void setGeRenQiangDan(boolean geRenQiangDan) {
        isGeRenQiangDan = geRenQiangDan;
    }

    public MapTopPopWindow(Context context, Activity activity, Marker marker) {
        this.mContext = context;
        this.mActivity = activity;
        this.marker = marker;
        mDatas = (MapDataBean.DataBean) marker.getObject();
        String jsonString = GsonUtil.createJsonString(mDatas);
        Log.e("点的数据", jsonString);
        init();
        initListener();

        Log.e("金纬度1", mDatas.lng + "--" + mDatas.lat);
        Log.e("金纬度2", Setting.getJinDu() + "--" + Setting.getWeiDu());
    }

    public MapTopPopWindow(Context context, Activity activity, Marker marker, boolean isGeRenQiangDan) {
        this.mContext = context;
        this.mActivity = activity;
        this.marker = marker;
        this.isGeRenQiangDan = isGeRenQiangDan;
        mDatas = (MapDataBean.DataBean) marker.getObject();
        String jsonString = GsonUtil.createJsonString(mDatas);
        Log.e("点的数据", jsonString);
        init();
        initListener();

        Log.e("金纬度1", mDatas.lng + "--" + mDatas.lat);
        Log.e("金纬度2", Setting.getJinDu() + "--" + Setting.getWeiDu());
    }


    private void initListener() {
        if (popupWindow != null) {
            //popWindow退出后 模糊背景取消
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
              /*  WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1f;
                mActivity.getWindow().setAttributes(lp);*/
                    marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(mContext.getResources(),
                                    R.mipmap.bashou)));
                }
            });
        }


    }

    private void init() {
        //3个参数的,填写视图,宽度,高度,
        //4个参数的:最后一个是是否获取焦点,true表示获取焦点
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_map_top_window, null);
        //设置详细信息的点击回调
        view.findViewById(R.id.map_pop_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onBackLitener != null) {
                    onBackLitener.onBackClick(mDatas);
                }
            }
        });

        //订单地址，点击可以导航及路线规划
        LinearLayout ll_muBiaoDi = view.findViewById(R.id.ll_muBiaoDi);
        if (isGeRenQiangDan) {
            ll_muBiaoDi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popw();
                }
            });
        }

        TextView danwei = view.findViewById(R.id.danwei);
        TextView map_pop_title = view.findViewById(R.id.map_pop_title);
        map_pop_title.setText(mDatas.shop_address);//设置地址
        TextView map_pop_name = view.findViewById(R.id.map_pop_name);
        map_pop_name.setText(mDatas.shop_name);//设置公司名字

        TextView map_pop_juli = view.findViewById(R.id.map_pop_juli);//距离
        TextView map_pop_day = view.findViewById(R.id.map_pop_day);//时间
        TextView map_pop_price = view.findViewById(R.id.map_pop_price);//价格
        TextView map_pop_daytime = view.findViewById(R.id.map_pop_daytime);//小时
        map_pop_day.setText(mDatas.day_count + "");
        if (!TextUtils.isEmpty(mDatas.day_count)) {
            int i = Integer.parseInt(mDatas.day_count);
            map_pop_daytime.setText(i * 24 + "小时");
        } else {
            map_pop_daytime.setText(0 + "小时");
        }
        map_pop_price.setText(mDatas.price);
        String lng = mDatas.lng;
        String lat = mDatas.lat;
        double jindu = Double.parseDouble(lat);
        double weidu = Double.parseDouble(lng);

        String jinDu = Setting.getJinDu();
        String weiDu = Setting.getWeiDu();
        double jinDud;
        double weiDud;
        if (TextUtils.isEmpty(jinDu)) {
            jinDud = Double.parseDouble("0.000000");
        } else {
            jinDud = Double.parseDouble(jinDu);
        }

        if (TextUtils.isEmpty(weiDu)) {
            weiDud = Double.parseDouble("0.000000");
        } else {
            weiDud = Double.parseDouble(weiDu);
        }
        LatLng start = new LatLng(weiDud, jinDud);
        LatLng end = new LatLng(weidu, jindu);
        Log.e("金纬度3", weiDud + "--" + jinDud);
        Log.e("金纬度4", weidu + "--" + jindu);
        int distance = (int) AMapUtils.calculateLineDistance(start, end);
        if (distance <= 1000) {
            map_pop_juli.setText(distance + "");
            danwei.setText("米");
        } else {
            int i = distance / 1000;
            map_pop_juli.setText(i + "");
            danwei.setText("千米");
        }

        //指定的popWindow显示
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //在popupWindow之外的区域可以触摸
        popupWindow.setOutsideTouchable(true);
        //设置 弹出后多余的模糊背景
       /* WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.5f;
        mActivity.getWindow().setAttributes(lp);*/
        //设置背景色(Drawable) ,颜色?
        Drawable drawable = new ColorDrawable(Color.alpha(R.color.transparent)); //透明色
        popupWindow.setBackgroundDrawable(drawable);

    }



    //弹框，路线规划，地图选择等
    private void popw() {

        View mView = LayoutInflater.from(mActivity).inflate(R.layout.layout_luxian_guihua, null);
        TextView tv_muBiaoDi = mView.findViewById(R.id.tv_muBiaoDi);
        tv_muBiaoDi.setText(mDatas.shop_address);
        TextView tv_daKaiGaoDe = mView.findViewById(R.id.tv_daKaiGaoDe);
        TextView tv_daKaiBaiDu = mView.findViewById(R.id.tv_daKaiBaiDu);
        TextView tv_xianShiLuXian = mView.findViewById(R.id.tv_xianShiLuXian);
        View view_line = mView.findViewById(R.id.view_line);
        View view_kong = mView.findViewById(R.id.view_kong);
        boolean bb = checkDeviceHasNavigationBar(mActivity);
        if(bb){

        }else {
            view_kong.setVisibility(View.GONE);
        }

        tv_xianShiLuXian.setVisibility(View.GONE);
        view_line.setVisibility(View.GONE);
        TextView tv_quXiao = mView.findViewById(R.id.tv_quXiao);

        final PopupWindow mPopupWindow = new PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setOutsideTouchable(true);
        Drawable drawable = new ColorDrawable(Color.alpha(R.color.transparent)); //透明色
        mPopupWindow.setBackgroundDrawable(drawable);
        mPopupWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0);

        tv_daKaiGaoDe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (isAvilible(mActivity, "com.autonavi.minimap")) {

                    Intent intent = new Intent("android.intent.action.VIEW",
                            Uri.parse("androidamap://keywordNavi?sourceApplication=cloud&keyword=" + mDatas.shop_address + "&style=2"));
                    intent.setPackage("com.autonavi.minimap");
                    mContext.startActivity(intent);
                    mPopupWindow.dismiss();
                } else {
                    showToast("您尚未安装高德地图！");
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    Intent intentt = new Intent(Intent.ACTION_VIEW, uri);
                    mContext.startActivity(intentt);
                }
            }
        });

        tv_daKaiBaiDu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isAvilible(mActivity, "com.baidu.BaiduMap")) {
                    try {
                        Intent intent3 = Intent.getIntent("intent://map/direction?origin=latlng:0,0|name:我的位置&destination=" + mDatas.shop_address + "&mode=drivingion=" + "上海" + "&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        mContext.startActivity(intent3);
                        mPopupWindow.dismiss();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast("您尚未安装百度地图！");
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intentt = new Intent(Intent.ACTION_VIEW, uri);
                    mContext.startActivity(intentt);
                }
            }
        });

        tv_xianShiLuXian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);
//                Intent mIntent = new Intent(mContext, OnePersonQiangDanActivity.class);
//                mIntent.putExtra("luxian",true);
//                mContext.startActivity(mIntent);
                mPopupWindow.dismiss();
            }
        });

        tv_quXiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });

    }



    private LatLonPoint mStartPoint = new LatLonPoint(31.336781, 121.494121);//起点，116.335891,39.942295
    private LatLonPoint mEndPoint = new LatLonPoint(31.395033, 121.501565);//终点，116.481288,39.995576
    private final int ROUTE_TYPE_DRIVE = 2;
    private RouteSearch mRouteSearch;

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        if (mStartPoint == null) {
            showToast("定位中，稍后再试...");
            return;
        }
        if (mEndPoint == null) {
            showToast("终点未设置");
        }
        mRouteSearch = new RouteSearch(mActivity);
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
            mRouteSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
                @Override
                public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

                }

                @Override
                public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                    final DrivePath drivePath = driveRouteResult.getPaths().get(0);

                }

                @Override
                public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

                }

                @Override
                public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

                }
            });
        }
    }


    public void show(LinearLayout view) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void show(View view) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void show(RelativeLayout view) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        //popupWindow.showAtLocation(view, Gravity.TOP, 0, mContext.getResources().getDimension(R.dimen.));
        popupWindow.showAsDropDown(view);
    }

    /**
     * ItemClick的回调接口
     *
     * @author zhy
     */
    public interface OnBackLitener {
        void onBackClick(MapDataBean.DataBean item);
    }

    private OnBackLitener onBackLitener;

    public void setOnItemClickLitener(OnBackLitener onBackLitener) {
        this.onBackLitener = onBackLitener;
    }


    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    //获取是否存在NavigationBar
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }


}
